//
//  MHChangeInformationListController.m
//  ManHua
//
//  Created by 赵永泉 on 15/10/31.
//  Copyright © 2015年 蓝欧科技. All rights reserved.
//

#import "MHChangeInformationListController.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "MHUserInfoSington.h"
#import "MHDataManager.h"
#import <RESideMenu.h>
#import "MBProgressHUD+MJ.h"
#import "MHChangeDateViewController.h"
#import "MHChangeNickViewController.h"
#import "MHChangeSignViewController.h"
#import "MHChangePasswordViewController.h"
#import "MHChangeFromViewController.h"


@interface MHChangeInformationListController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *userIcon;
@property (nonatomic, strong) UIImage *iconImg;
@property (weak, nonatomic) IBOutlet UILabel *nick;
@property (weak, nonatomic) IBOutlet UILabel *sex;
@property (weak, nonatomic) IBOutlet UILabel *birthday;
@property (weak, nonatomic) IBOutlet UILabel *desc;
@property (weak, nonatomic) IBOutlet UILabel *from;

@end

@implementation MHChangeInformationListController

- (void)setUserInfo:(MHUserInfo *)userInfo
{
    _userInfo = userInfo;
    self.userIcon.layer.cornerRadius = self.userIcon.frame.size.height / 2;
    self.userIcon.layer.masksToBounds = YES;
    if (self.userInfo.UserPhotoURL.length == 0) {
        self.userIcon.image = [UIImage imageNamed:@"akalin.jpg"];
    }
    else{
        [self.userIcon sd_setImageWithURL:[NSURL URLWithString:self.userInfo.UserPhotoURL] placeholderImage:[UIImage imageNamed:@"akalin"]];
    }
    self.birthday.text = self.userInfo.UserBorthday;
    if (self.userInfo.UserOther.length != 0) {
        self.desc.text = self.userInfo.UserOther;
    }
    if (self.userInfo.UserSex.length != 0) {
        self.sex.text = self.userInfo.UserSex;
    }
    self.nick.text = self.userInfo.UserNick;
    self.from.text = self.userInfo.UserForm;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.frame = CGRectMake(0, 64, Width, Height - 64);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak MHChangeInformationListController *test = self;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            NSLog(@"头像");
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更改图片" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
            UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                [self openCamera];
            }];
            UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                [self openAlbum];
                
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            [alert addAction:takePhotoAction];
            [alert addAction:albumAction];
            [alert addAction:cancelAction];
            
            [self presentViewController:alert animated:YES completion:nil];
        }
        else if (indexPath.row == 1)
        {
            NSLog(@"昵称");
            MHChangeNickViewController *nickVC = [[MHChangeNickViewController alloc]init];
            nickVC.userInfo = self.userInfo;
            nickVC.passInfoBlock = ^(MHUserInfo *userInfo){
                test.userInfo = userInfo;
                test.nick.text = userInfo.UserNick;
            };
            if (self.pushChangeDataBlock != nil) {
                self.pushChangeDataBlock(nickVC);
            }
        }
        else if (indexPath.row == 2)
        {
            NSLog(@"性别");
            UIAlertController *sexAlert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
            UIAlertAction *boyAction = [UIAlertAction actionWithTitle:@"男" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                self.sex.text = @"男";
                self.userInfo.UserSex = @"男";
                [self didClickSaveInfo];
            }];
            UIAlertAction *girlAction = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                self.sex.text = @"女";
                self.userInfo.UserSex = @"女";
                [self didClickSaveInfo];
            }];
            UIAlertAction *secrecyAction = [UIAlertAction actionWithTitle:@"保密" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                self.sex.text = @"保密";
                self.userInfo.UserSex = @"保密";
                [self didClickSaveInfo];
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [sexAlert addAction:boyAction];
            [sexAlert addAction:girlAction];
            [sexAlert addAction:secrecyAction];
            [sexAlert addAction:cancelAction];
            [self presentViewController:sexAlert animated:YES completion:nil];
        }
        else if (indexPath.row == 3)
        {
            NSLog(@"出生年月");
            MHChangeDateViewController *dateVC = [[MHChangeDateViewController alloc]init];
            dateVC.userInfo = self.userInfo;
            
            dateVC.passInfoBlock = ^(MHUserInfo *userInfo){
                test.userInfo = userInfo;
                test.birthday.text = userInfo.UserBorthday;
            };
            if (self.pushChangeDataBlock != nil) {
                self.pushChangeDataBlock(dateVC);
            }
        }
        else if (indexPath.row == 4)
        {
            NSLog(@"来自哪里");
            MHChangeFromViewController *fromVC = [[MHChangeFromViewController alloc]init];
            fromVC.userInfo = self.userInfo;
            fromVC.passInfoBlock = ^(MHUserInfo *userInfo){
                test.userInfo = userInfo;
                test.from.text = userInfo.UserForm;
            };
            if (self.pushChangeDataBlock != nil) {
                self.pushChangeDataBlock(fromVC);
            }
        }
        else if (indexPath.row == 5)
        {
            NSLog(@"个性签名");
            MHChangeSignViewController *signVC = [[MHChangeSignViewController alloc]init];
            signVC.userInfo = self.userInfo;
            signVC.passInfoBlock = ^(MHUserInfo *userInfo){
                test.userInfo = userInfo;
                test.desc.text = userInfo.UserOther;
            };
            if (self.pushChangeDataBlock != nil) {
                self.pushChangeDataBlock(signVC);
            }
        }
    }
    else if (indexPath.section == 1)
    {
        if (indexPath.row == 0) {
            NSLog(@"修改密码");
            MHChangePasswordViewController *changePasswordVC = [[MHChangePasswordViewController alloc]init];
            changePasswordVC.userid = [NSString stringWithFormat:@"%ld", self.userInfo.UserID];
            if (self.pushChangeDataBlock != nil) {
                self.pushChangeDataBlock(changePasswordVC);
            }
        }
    }
    else
    {
        NSLog(@"注销");
        NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
        UIAlertController *logoffAlert = [UIAlertController alertControllerWithTitle:@"选择" message:@"确认注销？" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"OK" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            if (self.changeHeaderBlock != nil) {
                self.changeHeaderBlock();
            }
            [user setBool:NO forKey:@"isLogin"];
            [user synchronize];
            [MHUserInfoSington sharedInstance].userInfo = nil;
            [[NSNotificationCenter defaultCenter]postNotificationName:@"logout" object:nil];
            NSLog(@"OK");
            
            if (self.returnRootLeftVCBlock != nil) {
                self.returnRootLeftVCBlock();
            }
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"手滑点错" style:(UIAlertActionStyleCancel) handler:nil];
        [logoffAlert addAction:OKAction];
        [logoffAlert addAction:cancelAction];
        [self presentViewController:logoffAlert animated:YES completion:nil];
    }
}

- (void)openCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;// 是否可编辑
        // 摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
        
    }else
    {
        
        NSLog(@"木有相机");
    }
}

- (void)openAlbum
{
    if ([UIImagePickerController isSourceTypeAvailable:(UIImagePickerControllerSourceTypePhotoLibrary)]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;//是否可以编辑
        
        //打开相册选择照片
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

//选中图片进入的代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    _iconImg = image;
    [picker dismissViewControllerAnimated:YES completion:nil];
    // 开始上传
    [self uploadUserIcon:image];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    // 得到照片
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    // 图片存入相册
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    
    self.iconImg = image;
    self.userIcon.image = _iconImg;
    // 开始上传
    [self uploadUserIcon:image];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadUserIcon:(UIImage *)image
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *parameters =@{@"userID":[NSString stringWithFormat:@"%ld", self.userInfo.UserID],@"method":@"uploadphoto"};
    
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    [MBProgressHUD showMessage:@"正在上传中"];
    NSLog(@"正在上传中");
    
    [manager POST:@"http://112.124.96.190:9090/manhuashenqi3yuansen/ComicHandle.ashx" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData :imageData name:@"file" fileName:@"file" mimeType:@"image/jpeg"];
        
    } success:^(AFHTTPRequestOperation *operation,id responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        if ([dict[@"UserResult"] integerValue] == 1) {
            
            MHUserInfo *userInfo = [[MHUserInfo alloc]init];
            [userInfo setValuesForKeysWithDictionary:dict[@"UserModel"]];
            self.userInfo = userInfo;
            userInfo.icon = image;
            self.userIcon.image = image;
            NSLog(@"%@", userInfo.icon);
            [MHUserInfoSington sharedInstance].userInfo = userInfo;
            [[MHDataManager shareManager] deleteUserInfo];
            [[MHDataManager shareManager] insertUserInfo:userInfo];
            [MBProgressHUD hideHUD];
            [MBProgressHUD showSuccess:@"上传成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUD];
            });
            NSLog(@"上传成功");
            [[NSNotificationCenter defaultCenter]postNotificationName:@"logout" object:nil];
            self.tableView.frame = CGRectMake(0, 64, Width, Height - 64);

        }
        
    } failure:^(AFHTTPRequestOperation *operation,NSError *error) {
        NSLog(@"Error: %@", error.localizedDescription);
        
    }];
}

- (void)didClickSaveInfo
{
    
    NSString *nick = [self.userInfo.UserNick stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *from = [self.userInfo.UserForm stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *userid = [NSString stringWithFormat:@"%ld", self.userInfo.UserID];
    NSString *birthday = self.userInfo.UserBorthday;
    NSString *other = [self.userInfo.UserOther stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *sex = [self.userInfo.UserSex stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *pathString = [NSString stringWithFormat:@"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx?method=changinfo&nick=%@&from=%@&userid=%@&birthday=%@&other=%@&sex=%@", nick, from, userid, birthday, other, sex];
    NSURLRequest *requset = [NSURLRequest requestWithURL:[NSURL URLWithString: pathString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError != nil) {
            NSLog(@"%@", connectionError.localizedDescription);
            return;
        }
        NSString *result=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        if ([result isEqualToString:@"1"]) {
            NSLog(@"修改成功");
        }
    }];
    
    
}


@end
